package cn.hdu.goods.user.service;

import cn.hdu.goods.user.dao.UserDao;
import cn.hdu.goods.user.domain.User;
import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;

import javax.mail.Session;
import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Properties;

/**
 * 用户模块业务层
 *
 * @author qdmmy6
 */
public class UserService {
    private UserDao userDao = new UserDao();


    public void regist(User user) {
        /**
         * 1.补齐其他数据id，状态，激活码
         */
        user.setUid(CommonUtils.uuid());
        user.setStatus(false);
        user.setActivationCode(CommonUtils.uuid() + CommonUtils.uuid());
        /**
         * 2.userDao把记录保存到数据库中
         */
        try {
            userDao.add(user);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        /**
         * 3.发邮件
         *   应该允许用户点击重发（自己后加）
         */
        Properties prop = new Properties();
        try {
            prop.load(this.getClass().getClassLoader().
                    getResourceAsStream("email_template.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String host = prop.getProperty("host");
        String name = prop.getProperty("username");
        String pass = prop.getProperty("password");
        Session session = MailUtils.createSession(host, name, pass);

        String from = prop.getProperty("from");
        String to = user.getEmail();
        String subject = prop.getProperty("subject");
        String content = MessageFormat.format(prop.getProperty("content"),user.getActivationCode());
        Mail mail = new Mail(from, to, subject, content);

        try {
            MailUtils.send(session, mail);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void activation(String activationCode) {

        try {
            User user = userDao.findByCode(activationCode);
            if (user == null) {
                new UserException("无效的激活码");
            }
            assert user != null;
            if (user.isStatus()) {
                new UserException("您已经激活过了，无需二次激活");
            }
            userDao.updateStatus(user.getUid(),true);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public User login(User user) {
        try {
            return userDao.findByNameAndPasswd(user.getLoginname(), user.getLoginpass());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void updatePassword(String uid, String newPass, String oldPass) throws UserException {
        System.out.println(uid+"  "+newPass+"  "+oldPass);
        try {
            boolean bool = userDao.findByUidAndPasswd(uid, oldPass);
            if (!bool) {
                throw new UserException("老密码错误");
            }
            userDao.updatePassword(uid, newPass);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 用户注册校验
     *
     * @param loginname
     * @return
     */
    public boolean ajaxValidateLoginname(String loginname) {
        try {
            return userDao.ajaxValidateLoginname(loginname);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * email校验
     *
     * @param email
     * @return
     */
    public boolean ajaxValidateEmail(String email) {
        try {
            return userDao.ajaxValidateEmail(email);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
